<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h2>聊天室</h2>
<label id="count"></label><br>
<div id="content"></div>
<input id="msg" type="text"/>
<input id="btn" type="button" value="发送"/>
<script>
    //初始化websocket对象
    const ws = new WebSocket('ws://localhost:8080/connect');
    //接收服务端的消息
    ws.onmessage = function(event) {
        let data = event.data;
        data = JSON.parse(data);
        if(data.type === 'chat') {
            let content = data.message.sendUser + " : " + data.message.sendDate + "<br>" + data.message.content + "<br>";
            document.getElementById('content').innerHTML += content + '<br>';
        } else if(data.type ==='total') {
            document.getElementById('count').innerText = "当前在线人数：" + data.message.total;
        }

    }
    //绑定事件发送消息
    document.getElementById('btn').addEventListener('click', function(){
        let message = document.getElementById('msg').value;
        ws.send(message);
    })
</script>
</body>
</html>